Telegram Group & Telegram Channel
🚀 Анонимные функции (лямбды) в C++

Лямбды — это удобные анонимные функции, которые можно объявлять прямо в коде. Вот ключевые фишки:

🔹 Базовый синтаксис

auto lambda = [] { /* тело функции */ };

Каждая лямбда имеет уникальный тип, даже если выглядит так же, как другая.

🔹Захват переменных
- По значению [x] — создаётся копия.
- По ссылке [&x] — работаем с оригиналом.


int a = 10, b = 10;
auto fn = [a, &b] {
a++; // Не влияет на оригинал
b++; // Меняет исходную переменную
};


🔹 Параметры и возвращаемое значение

auto sum = [](int x, int y) -> int { return x + y; };

Можно опустить -> int, если компилятор сам выведет тип.

🔹 Изменяемые лямбды (mutable)
Если захватываем по значению и хотим менять значение между вызовами:

int count = 0;
auto bump = [count]() mutable { ++count; };


🔹Обобщённые лямбды (C++14+)
Можно использовать auto для параметров:

auto sum = [](auto x, auto y) { return x + y; };


🔹Условная компиляция (if constexpr)
Позволяет обрабатывать разные типы по-разному:

auto print = [](auto x) {
if constexpr (std::is_same_v) {
std::cout << «int: " << x;
}
};


💡 Вывод:

Лямбды делают код лаконичнее, поддерживают захват переменных, обобщённые вычисления и даже constexpr-логику. Отлично заменяют мелкие функции и функторы.

➡️ @cpp_geek



tg-me.com/cpp_geek/320
Create:
Last Update:

🚀 Анонимные функции (лямбды) в C++

Лямбды — это удобные анонимные функции, которые можно объявлять прямо в коде. Вот ключевые фишки:

🔹 Базовый синтаксис


auto lambda = [] { /* тело функции */ };

Каждая лямбда имеет уникальный тип, даже если выглядит так же, как другая.

🔹Захват переменных
- По значению [x] — создаётся копия.
- По ссылке [&x] — работаем с оригиналом.


int a = 10, b = 10;
auto fn = [a, &b] {
a++; // Не влияет на оригинал
b++; // Меняет исходную переменную
};


🔹 Параметры и возвращаемое значение

auto sum = [](int x, int y) -> int { return x + y; };

Можно опустить -> int, если компилятор сам выведет тип.

🔹 Изменяемые лямбды (mutable)
Если захватываем по значению и хотим менять значение между вызовами:

int count = 0;
auto bump = [count]() mutable { ++count; };


🔹Обобщённые лямбды (C++14+)
Можно использовать auto для параметров:

auto sum = [](auto x, auto y) { return x + y; };


🔹Условная компиляция (if constexpr)
Позволяет обрабатывать разные типы по-разному:

auto print = [](auto x) {
if constexpr (std::is_same_v) {
std::cout << «int: " << x;
}
};


💡 Вывод:

Лямбды делают код лаконичнее, поддерживают захват переменных, обобщённые вычисления и даже constexpr-логику. Отлично заменяют мелкие функции и функторы.

➡️ @cpp_geek

BY C++ geek


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/cpp_geek/320

View MORE
Open in Telegram


C geek Telegram | DID YOU KNOW?

Date: |

Look for Channels Online

You guessed it – the internet is your friend. A good place to start looking for Telegram channels is Reddit. This is one of the biggest sites on the internet, with millions of communities, including those from Telegram.Then, you can search one of the many dedicated websites for Telegram channel searching. One of them is telegram-group.com. This website has many categories and a really simple user interface. Another great site is telegram channels.me. It has even more channels than the previous one, and an even better user experience.These are just some of the many available websites. You can look them up online if you’re not satisfied with these two. All of these sites list only public channels. If you want to join a private channel, you’ll have to ask one of its members to invite you.

Telegram auto-delete message, expiring invites, and more

elegram is updating its messaging app with options for auto-deleting messages, expiring invite links, and new unlimited groups, the company shared in a blog post. Much like Signal, Telegram received a burst of new users in the confusion over WhatsApp’s privacy policy and now the company is adopting features that were already part of its competitors’ apps, features which offer more security and privacy. Auto-deleting messages were already possible in Telegram’s encrypted Secret Chats, but this new update for iOS and Android adds the option to make messages disappear in any kind of chat. Auto-delete can be enabled inside of chats, and set to delete either 24 hours or seven days after messages are sent. Auto-delete won’t remove every message though; if a message was sent before the feature was turned on, it’ll stick around. Telegram’s competitors have had similar features: WhatsApp introduced a feature in 2020 and Signal has had disappearing messages since at least 2016.

C geek from us


Telegram C++ geek
FROM USA